package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserLoginService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import io.jsonwebtoken.Jwt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



/**
 * @author iTaotao
 * @version 1.0
 * @Description
 * @createTime 2023年08月01日 10:55:00
 */
@Service
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public UserLoginVO login(String code) {

        //1.把code发给微信服务器,校验,取openid
        Map<String, String> map = new HashMap<>(8);
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");

        String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", map);
        log.info("s参数:{}", s);
        JSONObject jsonObject = JSON.parseObject(s);
        String openid = jsonObject.getString("openid");
        log.info("返回结果:{}", openid);


        //2.把openid存起来?
        User user = userMapper.selectUserByOpenId(openid);
        if(Objects.isNull(user)){
            //2.1不存在,说明用户首次登录,重新创建新用户
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }
        //2.2存在,直接返回

        //3.生成令牌返回

        HashMap<String, Object> clams = new HashMap<>(8);
        clams.put(JwtClaimsConstant.USER_ID , user.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), clams);
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setOpenid(openid);
        userLoginVO.setToken(jwt);
        return userLoginVO;
    }
}
